package com.lt.controller;

import com.lt.service.COSFileService;
import com.lt.utils.JwtUtils;
import com.lt.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

/**
 * @Author :liteng
 * @Time : 2023-10-22 17:20
 */

@Slf4j
@RestController

@RequestMapping("/file")
public class FileController {

    private final COSFileService cosFileService;

    public FileController(COSFileService cosFileService) {
        this.cosFileService = cosFileService;
    }

    /**
     * 提交文件
     *
     * @param file 要上传的文件
     * @return 文件路径
     */
    @PostMapping
    public Result Upload(@RequestHeader(value = "token") String jwt, MultipartFile file) {

        if (file == null || file.isEmpty()) {
            return Result.error("文件为空");
        }
        String originalFilename = file.getOriginalFilename();
        log.info("上传的源文件名称:" + originalFilename);

//        file.transferTo(new File("C:\\AMyFile\\yanjiusheng\\"+originalFilename));
        //操作用户num
        Long num = JwtUtils.getNumFromJwt(jwt);
        //获得下载路径
        String[] url = cosFileService.upload(file, num);

        HashMap<String, String> map = new HashMap<>();
        map.put("fileName", originalFilename);
        map.put("fileId", url[0]);
        map.put("fileUrl", url[1]);
        return Result.success(map);
    }

}
